<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>考试答题</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/layui@2.6.8/dist/css/layui.css">
    <style>
        body { margin:0; font-family: "Microsoft YaHei", sans-serif; }
        .top { background:#009688; color:#fff; padding:15px; display:flex; align-items:center; }
        .top .toggle, .top .user { cursor:pointer; margin-right:20px; }
        .flexarea { display:flex; height:calc(100vh - 60px); }
        .sidebar { width:220px; background:#f5f5f5; overflow:auto; padding:10px; }
        .sidebar ul { list-style:none; padding:0; margin:0; }
        .sidebar li { margin-bottom:8px; }
        .sidebar a { display:inline-block; width:32px; height:32px; line-height:32px; text-align:center; border:1px solid #ccc; border-radius:4px; background:#fff; }
        .sidebar a.active { background:#009688; color:#fff; }
        .main { flex:1; padding:20px; overflow:auto; }
        .question { margin-bottom:20px; }
        .analysis { margin-top:15px; background:#f0f9ff; padding:10px; border-left:3px solid #009688; }
        .operation { text-align:center; margin-top:20px; }
        .operation button { margin:0 10px; }
    </style>
</head>
<body>
<div class="top">
    <span class="toggle layui-icon layui-icon-menu"></span>
    <span class="examInfo"></span>
    <div class="user">
        <span class="layui-icon layui-icon-user"></span>
        <div class="userinfo layui-hide">
            <p>姓名：<span class="username"></span></p>
            <p>准考证号：<span class="userid"></span></p>
        </div>
    </div>
    <div class="timer" style="margin-left:auto;"></div>
</div>
<div class="flexarea">
    <div class="sidebar layui-hide"></div>
    <div class="main">
        <div class="question">
            <div><strong id="qnumber"></strong>. <span id="qtext"></span></div>
            <div id="options"></div>
        </div>
        <div id="analysis" class="analysis layui-hide"></div>
        <div class="operation">
            <button id="prev" class="layui-btn">上 一 题</button>
            <button id="mark" class="layui-btn layui-btn-warm">标 记</button>
            <button id="next" class="layui-btn">下 一 题</button>
            <button id="finish" class="layui-btn layui-btn-danger">交 卷</button>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/layui@2.6.8/dist/layui.js"></script>
<script>
    layui.use(['layer'], function(){
        const layer = layui.layer;
        const examCode = new URLSearchParams(location.search).get('examCode');
        if (!examCode) return layer.msg('缺少考试编号');

        let examData, topic = {}, currentType = 1, index = 0;
        let radioAnswers = {}, markFlags = {};

        // 1. 先查考试信息
        axios.get(`/exam/${examCode}`).then(res=>{
            examData = res.data.data;
            document.querySelector('.examInfo').innerText = `${examData.type} - ${examData.source}`;
            // 从 Cookie 获取用户信息
            const name = layui.data('login').username || '';
            const id = layui.data('login').studentId || '';
            document.querySelector('.username').innerText = name;
            document.querySelector('.userid').innerText = id;
            // 2. 再查试卷题目
            return axios.get(`/paper/${examData.paperId}`);
        }).then(res2=>{
            topic = res2.data;
            buildSidebar();
            loadQuestion();
            startTimer(examData.totalTime);
        });

        function buildSidebar(){
            const sb = document.querySelector('.sidebar');
            sb.innerHTML = '';
            ['1','2','3'].forEach(type=>{
                const arr = topic[type]||[];
                arr.forEach((q,i)=>{
                    const a = document.createElement('a');
                    a.innerText = (type-1)*100 + i + 1;
                    a.onclick = ()=>{ currentType=+type; index=i; loadQuestion(); };
                    sb.appendChild(a);
                });
            });
            sb.classList.remove('layui-hide');
        }

        function loadQuestion(){
            const q = (topic[currentType]||[])[index];
            if (!q) return;
            document.getElementById('qnumber').innerText = (currentType-1)*100 + index +1;
            document.getElementById('qtext').innerText = q.question;
            const optDiv = document.getElementById('options');
            optDiv.innerHTML = '';
            if (currentType===1 || currentType===3) {
                ['A','B','C','D'].forEach((label,i)=>{
                    if (currentType===3 && i>=2) return;
                    const r = document.createElement('input');
                    r.type='radio'; r.name='opt'; r.value= label;
                    if (radioAnswers[q.questionId]===label) r.checked=true;
                    r.onchange=()=>{ radioAnswers[q.questionId]=label; markFlags[q.questionId]=true; updateSidebar(); showAnalysis(); };
                    optDiv.appendChild(r);
                    const lab = document.createTextNode(' '+label+' '+q['answer'+label]);
                    optDiv.appendChild(lab);
                    optDiv.appendChild(document.createElement('br'));
                });
            }

            document.getElementById('analysis').classList.toggle('layui-hide', !markFlags[q.questionId]);

            updateSidebar();
            layui.element && layui.element.render();
        }

        function updateSidebar(){
            const links = document.querySelectorAll('.sidebar a');
            links.forEach((a,i)=>{
                const cid = +a.innerText;
                a.classList.toggle('active', i===((currentType-1)*100+index));
            });
        }

        document.getElementById('prev').onclick = ()=>{
            if (index>0) index--; loadQuestion();
        };
        document.getElementById('next').onclick = ()=>{
            if (index+1 < (topic[currentType]||[]).length) index++; loadQuestion();
        };
        document.getElementById('mark').onclick = ()=>{
            const qid = topic[currentType][index].questionId;
            markFlags[qid] = !markFlags[qid];
            updateSidebar();
        };

        document.getElementById('finish').onclick = ()=>layer.confirm('确认交卷？',{},ok=>commit());

        function commit(){
            let score=0;
            Object.keys(radioAnswers).forEach(qid=>{
                for(let t=1;t<=3;t++){
                    const arr = topic[t]||[];
                    const q = arr.find(x=>x.questionId==qid);
                    if (q && radioAnswers[qid]===q.rightAnswer) score+=q.score;
                }
            });
            axios.post('/score',{examCode,studentId:layui.data('login').studentId,subject:examData.source,etScore:score,answerDate:new Date().toISOString().slice(0,10)})
                .then(()=>location.href='/view/student/myScore.html?score='+score);
        }

        function startTimer(mins){
            const el = document.querySelector('.timer');
            let s = mins * 60;
            const iv = setInterval(()=>{
                s--;
                const m = Math.floor(s/60), sec = s%60;
                el.innerText = '倒计时：'+ m + '分' + sec + '秒';
                if (s<=0){ clearInterval(iv); commit(); }
            },1000);
        }
    });
</script>
</body>
</html>
